﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Cz.CzRpcReflection
{
    public class CzRpcReflection : ICzRpc
    {
        [CzServiceField] private ICzLog log;
        [CzServiceField] private ICzConfig config;

        private bool debug;
        private readonly CzMethodList methodList;
        private readonly Dictionary<string, MethodInfo> methods;
        
        public CzRpcReflection(CzMethodList methodList)
        {
            this.methodList = methodList;
            methods = methodList.GetType()
                .GetMethods(~BindingFlags.Static | BindingFlags.Public)
                .ToDictionary(method => method.Name);
        }
        
        public void Start()
        {
            ReLoadConfig();
            config.OnChange += ReLoadConfig;
            
            log.Info("CzRpcReflection start");
            if (debug)
            {
                log.Info("CzRpcReflection methods", methods.ToJson());
            }
        }

        public object Dispatch(string name, params object[] parameters)
        {
            if(!methods.TryGetValue(name, out var methodInfo))
                throw new Exception($"方法不存在:{name}");

            return methodInfo.Invoke(methodList, parameters);
        }
        
        private void ReLoadConfig()
        {
            debug = config.GetWithDefault(false, "rpc_reflection", "debug");
        }
    }

    public abstract class CzMethodList
    {
        
    }
}